package com.chinawayltd.ews.sample.util.spring;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public final class SpringContextUtil implements ApplicationContextAware {
	private static ApplicationContext ctx;
	
	public static <T> T getBean(String beanName){
		if(StringUtils.isBlank(beanName)){
			throw new RuntimeException("beanName must be not blank!");
		}
		return (T)ctx.getBean(beanName);
	}

	public static <T> T getBean(Class<T> clazz){
		if(clazz == null){
			throw new RuntimeException("clazz must be not blank!");
		}
		return ctx.getBean(clazz);
	}

	public static boolean containsBean(String beanName) {
		return SpringContextUtil.ctx.containsBean(beanName);
	}

	public static ApplicationContext getApplicationContext() {
		return SpringContextUtil.ctx;
	}

	/**
	 * 实现ApplicationContextAware接口的回调方法，设置上下文环境
	 * 
	 * @throws BeansException
	 */
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		SpringContextUtil.ctx = ctx;
	}
}
